package com.example.administrator.hqq.activity.post;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.View.KeyboardLayout;
import com.example.administrator.hqq.View.MyGridView;
import com.example.administrator.hqq.View.alertview.AlertViewFactory;
import com.example.administrator.hqq.adapter.discover.ReleasePostAdapter;
import com.example.administrator.hqq.base.MyActivity;
import com.example.administrator.hqq.bean.ForumComment;
import com.example.administrator.hqq.bean.QNTokenBean;
import com.example.administrator.hqq.bean.post.MyGroupListBean;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.utils.BoldTextUtils;
import com.example.administrator.hqq.utils.CameraUtils;
import com.example.administrator.hqq.utils.GetLocationUtils;
import com.example.administrator.hqq.utils.HintWordsUtils;
import com.example.administrator.hqq.utils.MyTextUtils;
import com.example.administrator.hqq.utils.UploadManagerUtils;
import com.example.administrator.hqq.utils.transform.GlideCircleTransform;
import com.google.gson.Gson;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class ReleasePostActivity extends MyActivity {
    @BindView(R.id.return_auto)
    AutoRelativeLayout returnAuto;
    @BindView(R.id.release_post)
    AutoRelativeLayout releasePost;
    @BindView(R.id.topTitle_auto)
    AutoRelativeLayout topTitleAuto;
    @BindView(R.id.context_post)
    EditText contextPost;
    @BindView(R.id.post_image)
    MyGridView postImage;
    @BindView(R.id.scrollView)
    ScrollView scrollView;
    @BindView(R.id.man)
    RadioButton man;
    @BindView(R.id.woman)
    RadioButton woman;
    @BindView(R.id.man_unlimited)
    RadioButton manUnlimited;
    @BindView(R.id.gender_prefer)
    RadioGroup genderPrefer;
    @BindView(R.id.age)
    RadioButton age;
    @BindView(R.id.age_unlimited)
    RadioButton ageUnlimited;
    @BindView(R.id.age_prefer)
    RadioGroup agePrefer;
    @BindView(R.id.screen_auto)
    AutoLinearLayout screenAuto;
    @BindView(R.id.aibum)
    ImageView aibum;
    @BindView(R.id.camera)
    ImageView camera;
    @BindView(R.id.forum_guide)
    ImageView forumGuide;
    @BindView(R.id.keyboardLayout)
    KeyboardLayout keyboardLayout;
    @BindView(R.id.exhibition_group)
    AutoLinearLayout exhibitionGroup;
    @BindView(R.id.group_image)
    ImageView groupImage;
    @BindView(R.id.group_title)
    TextView groupTitle;
    @BindView(R.id.people_number)
    TextView peopleNumber;
    @BindView(R.id.number_auto)
    AutoLinearLayout numberAuto;
    @BindView(R.id.group_introduce)
    TextView groupIntroduce;
    @BindView(R.id.delete_group)
    ImageView deleteGroup;
    @BindView(R.id.group_item)
    AutoRelativeLayout groupItem;
    @BindView(R.id.bottom_view)
    AutoLinearLayout bottomView;
    @BindView(R.id.age_number)
    TextView ageNumber;
    @BindView(R.id.age_auto)
    AutoLinearLayout ageAuto;
    @BindView(R.id.location_number)
    TextView locationNumber;
    @BindView(R.id.location_auto)
    AutoLinearLayout locationAuto;
    @BindView(R.id.view1)
    View view1;
    @BindView(R.id.view2)
    View view2;
    @BindView(R.id.view3)
    View view3;
    private String gender_prefer;
    private String chat_permission = "1";
    private String reply_permission = "1";
    private String age_prefer;
    private String location_prefer = "0";
    private String TAG = this.getClass().getSimpleName();
    private QNTokenBean qnTokenBean;
    private String forumId = "";
    private List<String> url;
    private ReleasePostAdapter releasePostAdapter;
    private String picUrl;
    private List<String> pic;
    private MyGroupListBean myGroupListBean;
    private boolean isShowDlalog = false;
    private String groupID = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release_post);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        boolean aBoolean = SPUtils.getInstance().getBoolean(LoongsConfig.first_forum_create, true);
        if (aBoolean) {
            forumGuide.setVisibility(View.VISIBLE);
            SPUtils.getInstance().put(LoongsConfig.first_forum_create, false);
            Handler handler = new Handler();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                }
            });
        }
        indata();
        initview();
        getMyGroup();
    }

    @Override
    protected void onResume() {
        screenAuto.setVisibility(View.VISIBLE);
        keyboardLayout.requestLayout();
        scrollView.requestLayout();
        super.onResume();
    }

    private void initview() {
        url = new ArrayList<>();
        pic = new ArrayList<>();
        releasePostAdapter = new ReleasePostAdapter(this, url);
        postImage.setAdapter(releasePostAdapter);
        postImage.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            }
        });
        releasePostAdapter.setDeletePic(new ReleasePostAdapter.DeletePic() {
            @Override
            public void delete(int position) {
                pic.remove(position);
                url.remove(position);
                releasePostAdapter.notifyDataSetChanged();
            }
        });
        keyboardLayout.setOnkbdStateListener(new KeyboardLayout.onKeyboaddsChangeListener() {
            @Override
            public void onKeyBoardStateChange(int state) {
                switch (state) {
                    case KeyboardLayout.KEYBOARD_STATE_HIDE: //
                        Log.e(TAG, "软键盘隐藏: ");
                        screenAuto.setVisibility(View.VISIBLE);
                        keyboardLayout.requestLayout();
                        scrollView.requestLayout();
                        break;
                    case KeyboardLayout.KEYBOARD_STATE_SHOW:
                        Log.e(TAG, "软键盘弹起");
                        screenAuto.setVisibility(View.GONE);
                        keyboardLayout.requestLayout();
                        scrollView.requestLayout();
                        break;
                }
            }
        });
        groupItem.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                deleteGroup.setVisibility(View.VISIBLE);
                return false;
            }
        });
    }

    private void indata() {
        OkHttpUtils.get().url(UrlFactory.getPrepare_add())
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e);
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt(LoongsConfig.code) == 200) {
                        forumId = jsonObject.getString(LoongsConfig.forum_id);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @OnClick({R.id.delete_group, R.id.forum_guide, R.id.return_auto, R.id.release_post, R.id.man, R.id.woman, R.id.exhibition_group, R.id.man_unlimited, R.id.age, R.id.age_unlimited, R.id.age_prefer, R.id.aibum, R.id.camera})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.delete_group:
                groupID = "";
                deleteGroup.setVisibility(View.GONE);
                exhibitionGroup.setVisibility(View.VISIBLE);
                groupItem.setVisibility(View.GONE);
                break;
            case R.id.forum_guide:
                forumGuide.setVisibility(View.GONE);
                break;
            case R.id.return_auto:
                finish();
                break;
            case R.id.release_post:
                picUrl = "";
                if (pic.size() > 0) {
                    for (int i = 0; i < pic.size(); i++) {
                        if (i == 0) {
                            picUrl += pic.get(i);
                        } else {
                            picUrl += "," + pic.get(i);
                        }
                    }
                }
                if (TextUtils.isEmpty(contextPost.getText())) {
                    Toast.makeText(this, "请把帖子的内容补充完整", Toast.LENGTH_SHORT).show();
                    break;
                }
                if (MyTextUtils.isEmptyString(contextPost)) {
                    Toast.makeText(this, "帖子的内容不能全是空格", Toast.LENGTH_SHORT).show();
                    break;
                }

//                if (MyTextUtils.isEmptyString(titlePost)) {
//                    Toast.makeText(this, "帖子的标题不能全是空格", Toast.LENGTH_SHORT).show();
//                    break;
//                }
                if (TextUtils.isEmpty(location_prefer) || TextUtils.isEmpty(gender_prefer) || TextUtils.isEmpty(age_prefer)) {
                    Toast.makeText(this, "请把帖子筛选项补齐", Toast.LENGTH_SHORT).show();
                } else {
                    OkHttpUtils.get().url(UrlFactory.getforumadd())
                            .addParams(LoongsConfig.forum_id, forumId)
                            .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                            .addParams(LoongsConfig.topic_id, getIntent().getStringExtra(LoongsConfig.topic_id))
                            .addParams(LoongsConfig.location, GetLocationUtils.getLocation())
                            .addParams(LoongsConfig.city_code, GetLocationUtils.getCityCode())
                            .addParams(LoongsConfig.title, "")
                            .addParams(LoongsConfig.group_id, groupID)
                            .addParams(LoongsConfig.chat_permission, chat_permission)
                            .addParams(LoongsConfig.reply_permission, reply_permission)
                            .addParams(LoongsConfig.location_prefer, location_prefer)
                            .addParams(LoongsConfig.gender_prefer, gender_prefer)
                            .addParams(LoongsConfig.age_prefer, age_prefer)
                            .addParams(LoongsConfig.text, contextPost.getText().toString())
                            .addParams(LoongsConfig.url, picUrl)
                            .build().execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Log.e(TAG, "创建帖子onError: " + e.getMessage());
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            Log.e(TAG, "创建帖子onResponse: " + response);
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                HintWordsUtils.showMarkeWords(jsonObject.getInt(LoongsConfig.code), jsonObject.getString(LoongsConfig.description));
                                if (jsonObject.getInt(LoongsConfig.code) == 200) {
                                    ForumComment forumComment = new ForumComment(ForumComment.Type.CREATE_FORUM, "", -1);
                                    EventBus.getDefault().post(forumComment);
                                    finish();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
                break;
//            case R.id.locality:
//                location_prefer = "1";
//                setPitchUpTextColor(locality);
//                break;
//            case R.id.locality_unlimited:
//                setPitchUpTextColor(localityUnlimited);
//                location_prefer = "0";
//                break;
            case R.id.man:
                gender_prefer = "1";
                setPitchUpTextColor(man);
                break;
            case R.id.woman:
                gender_prefer = "2";
                setPitchUpTextColor(woman);
                break;
            case R.id.man_unlimited:
                gender_prefer = "0";
                setPitchUpTextColor(manUnlimited);
                break;
            case R.id.age:
                age_prefer = "1";
                setPitchUpTextColor(age);
                break;
            case R.id.age_unlimited:
                age_prefer = "0";
                setPitchUpTextColor(ageUnlimited);
                break;
            case R.id.aibum:
                if (url.size() != 6)
                    ReleasePostActivityPermissionsDispatcher.startStorageWithCheck(ReleasePostActivity.this);
                break;
            case R.id.camera:
                if (url.size() != 6)
                    ReleasePostActivityPermissionsDispatcher.startLocationWithCheck(ReleasePostActivity.this);
                break;
            case R.id.exhibition_group:
                isShowDlalog = true;
                if (myGroupListBean == null || myGroupListBean != null && myGroupListBean.getData().size() == 0) {
                    getMyGroup();
                } else {
                    showAddGroupDialog();
                }
                break;
        }
    }

    private void showAddGroupDialog() {
        AlertViewFactory.getInstance().showReleaseForumAddGroup(ReleasePostActivity.this, myGroupListBean.getData(), new AlertViewFactory.OnSelectGroupListener() {
            @Override
            public void getSelectGroupID(String groupId, int position) {
                groupID = groupId;
                exhibitionGroup.setVisibility(View.GONE);
                groupItem.setVisibility(View.VISIBLE);
                deleteGroup.setVisibility(View.VISIBLE);
                Glide.with(ReleasePostActivity.this).load(myGroupListBean.getData().get(position).getUrl()).bitmapTransform(new GlideCircleTransform(ReleasePostActivity.this)).into(groupImage);
                groupTitle.setText(myGroupListBean.getData().get(position).getTitle());
                BoldTextUtils.BoldText(groupTitle);
                peopleNumber.setText(myGroupListBean.getData().get(position).getMember_amount() + "");
                groupIntroduce.setText(myGroupListBean.getData().get(position).getIntroduction());

                ageNumber.setText(myGroupListBean.getData().get(position).getSame_age_count() + "");
                locationNumber.setText(myGroupListBean.getData().get(position).getSame_city_count() + "");
                if (myGroupListBean.getData().get(position).getSame_age_count() == 0) {
                    locationAuto.setVisibility(View.GONE);
                } else {
                    locationAuto.setVisibility(View.VISIBLE);
                }
                if (myGroupListBean.getData().get(position).getSame_city_count() == 0) {
                    ageAuto.setVisibility(View.GONE);
                } else {
                    ageAuto.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    public void setPitchUpTextColor(RadioButton rad) {
        switch (rad.getId()) {
//            case R.id.locality:
//            case R.id.locality_unlimited:
//                locality.setTextColor(Color.parseColor("#8D8D8D"));
//                localityUnlimited.setTextColor(Color.parseColor("#8D8D8D"));
//                break;
            case R.id.man:
            case R.id.woman:
            case R.id.man_unlimited:
                man.setTextColor(Color.parseColor("#8D8D8D"));
                woman.setTextColor(Color.parseColor("#8D8D8D"));
                manUnlimited.setTextColor(Color.parseColor("#8D8D8D"));
                break;
            case R.id.age:
            case R.id.age_unlimited:
                age.setTextColor(Color.parseColor("#8D8D8D"));
                ageUnlimited.setTextColor(Color.parseColor("#8D8D8D"));
                break;
        }
        rad.setTextColor(Color.parseColor("#4B8978"));
    }


    /**
     * 申请权限
     */
    @SuppressLint("NoCorrespondingNeedsPermission")
    @OnShowRationale({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRationaleForLocation(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage("申请相机权限")
                .setPositiveButton("同意", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    @OnPermissionDenied({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showDeniedForLocation() {
        Toast.makeText(this, getString(R.string.permission_denied), Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showNeverAskForLocation() {
        Toast.makeText(this, getString(R.string.permission_never_ask), Toast.LENGTH_SHORT).show();
    }

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void startLocation() {
        CameraUtils.getInstance().takeCamera(this);
    }

    @OnShowRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void showRetionaleForStorage(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage(getString(R.string.storage_permission))
                .setPositiveButton(getString(R.string.agree), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton(getString(R.string.refuse), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    @OnNeverAskAgain(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void showNeverAskForStorage() {
        Toast.makeText(this, getString(R.string.permission_never_ask), Toast.LENGTH_SHORT).show();
    }

    @OnPermissionDenied(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void showDeniedForStorage() {
        Toast.makeText(this, getString(R.string.permission_denied), Toast.LENGTH_SHORT).show();
    }

    @NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    public void startStorage() {
        CameraUtils.getInstance().openAlbum(this);
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        ReleasePostActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e(TAG, "onActivityResult: " + data);
        CameraUtils.getInstance().onActivityResult(this, requestCode, resultCode, data, new CameraUtils.OnResultListener() {
            @Override
            public void takePhotoFinish(String path) {
                File picFile = new File(path);
                if (picFile.exists()) {
                    getQNToken(path);
                }
            }

            @Override
            public void selectPictureFinish(String path) {
                File picFile = new File(path);
                if (picFile.exists()) {
                    getQNToken(path);
                }
            }

            @Override
            public void cropPictureFinish(String path) {
            }
        });
    }

    public void getQNToken(String path) {
        showLoadingDialog();
        final File picFile = new File(path);
        OkHttpUtils.get().url(UrlFactory.getQNToken())
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.type, LoongsConfig.FORUM)
                .addParams(LoongsConfig.id, forumId)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e.getMessage());
                dismissLoadingDialog();
            }

            @Override
            public void onResponse(String s, int id) {
                Log.e(TAG, "onResponse: " + s);
                final Gson gson = new Gson();
                qnTokenBean = gson.fromJson(s, QNTokenBean.class);
                if (qnTokenBean.getCode() == 200)
                    UploadManagerUtils.getUploadManager().put(picFile, qnTokenBean.getKey(), qnTokenBean.getToken(), new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject res) {
                            //res包含hash、key等信息，具体字段取决于上传策略的设置
                            if (info.isOK()) {
                                Log.i("qiniu", "res");
                                url.add(qnTokenBean.getUrl());
                                Log.e(TAG, "Url: " + qnTokenBean.getUrl());
                                pic.add(qnTokenBean.getId());
                                releasePostAdapter.notifyDataSetChanged();
                            } else {
                            }
                            dismissLoadingDialog();
                            Log.e("qiniu", key + ", " + info + ", " + res);
                        }
                    }, null);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(String s) {

    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected String getActivityName() {
        return this.getClass().getSimpleName();
    }

    public void getMyGroup() {
        OkHttpUtils.get().url(UrlFactory.getMyGroup())
                .addParams(LoongsConfig.user_id, LoongsConfig.getUser_id())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "获取自己管理的群onError: " + e.getMessage());
                if (isShowDlalog)
                    ToastUtils.showShort("暂时未查到您管理的群");
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "获取自己管理的群onResponse: " + response);
                Gson gson = new Gson();
                myGroupListBean = gson.fromJson(response, MyGroupListBean.class);
                if (myGroupListBean.getCode() == 200) {
                    if (myGroupListBean.getData() == null || myGroupListBean.getData().size() == 0) {
                        if (isShowDlalog)
                            ToastUtils.showShort("暂时未查到您管理的群");
                    } else {
                        if (isShowDlalog) {
                            showAddGroupDialog();
                        }
                    }
                } else {
                    if (isShowDlalog)
                        ToastUtils.showShort("暂时未查到您管理的群");
                }
            }
        });
    }
}
